import time, random
from django.db import models, transaction


class OrderDetailManager(models.Manager):

    def create_order_detail(self, order, price, discount, total_money, type, total_integral, total_discount_money,  **extra_fields):
        with transaction.atomic():
            order_detail = self.model(price=price,
                                      good=extra_fields['good'],
                                      num=extra_fields['num'],
                                      totalMoney=total_money,
                                      totalActualCharge=extra_fields['totalActualCharge'],
                                      totalDiscountMoney=total_discount_money,
                                      order=order,
                                      discount=discount
                                      )
            order_detail.type = type
            if type == 2:
                order_detail.total_integral = total_integral

            order_detail.save(using=self.db)


class OrderManager(models.Manager):

    def create_order_num(self):
        # 下单时间的年月日12+随机数4位
        local_time = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))[2:]
        result = local_time + str(random.randint(1000, 9999))
        return result

    def create_order(self, **extra_fields):
        with transaction.atomic():
            orderId = extra_fields['orderId']
            order = self.model(orderId=extra_fields['orderId'],
                               user=extra_fields['user'],
                               totalActualCharge=0,
                               totalMoney=0,
                               total_integral=0,
                               note=extra_fields['note'],
                               type=extra_fields['type']
                               )
            records = None
            try:
                records = extra_fields['records']
                del extra_fields['records']
            except:
                pass

            order.save(using=self._db)
            if records:
                order.records.add(*records)
            return order
